<template>
  <div class="page-decoration-container">
    <div class="page-decoration">
      <!-- 左侧模块选择菜单 -->
      <div class="left-panel">
        <el-menu :default-active="activeMenuKey" @select="handleMenuSelect" class="menu">
          <el-menu-item v-for="(menu, key) in pageMap" :key="key" :index="key">
            {{ menu.name }}
          </el-menu-item>
        </el-menu>
      </div>

      <!-- 中间和右侧主工作区 -->
      <div class="main-panel" v-loading="loading">
        <!-- 核心修复：使用 v-if 确保 activeConfigData 非 null 时才渲染子模块 -->
        <component v-if="activeConfigData !== null" :is="activeMenu.component" :config.sync="activeConfigData" />
        <!-- 数据加载中或失败时显示占位符 -->
        <div v-else class="initial-loading">
          数据加载中...
        </div>
      </div>
    </div>

    <!-- 底部固定的保存按钮 -->
    <div class="footer-bar">
      <el-button type="primary" @click="handleSave" :loading="saving" size="medium">保 存</el-button>
    </div>
  </div>
</template>

<script>
  // 引入所有子组件
  import HomeModule from './modules/HomeModule.vue';
  import UserCenterModule from './modules/UserCenterModule.vue';
  import CustomerServiceModule from './modules/CustomerServiceModule.vue';
  import TabBarModule from './modules/TabBarModule.vue';

  import {
    getPageData,
    savePageData
  } from "@/api/iot/decoratePage";

  // 静态页面模块映射
  const PAGE_MAP = {
    home: {
      key: 'home',
      type: 1,
      name: '首页装修',
      component: 'HomeModule',
      dataType: 'array'
    },
    userCenter: {
      key: 'userCenter',
      type: 2,
      name: '个人中心',
      component: 'UserCenterModule',
      dataType: 'array'
    },
    customerService: {
      key: 'customerService',
      type: 3,
      name: '客服设置',
      component: 'CustomerServiceModule',
      dataType: 'object'
    },
    tabBar: {
      key: 'tabBar',
      type: 4,
      name: '底部导航',
      component: 'TabBarModule',
      dataType: 'object'
    },
  };

  export default {
    name: "PageDecoration",
    components: {
      HomeModule,
      UserCenterModule,
      CustomerServiceModule,
      TabBarModule
    },
    data() {
      return {
        activeMenuKey: 'home',
        loading: false,
        saving: false,
        pageDataStore: {},
      };
    },
    computed: {
      pageMap() {
        return PAGE_MAP;
      },
      activeMenu() {
        return this.pageMap[this.activeMenuKey];
      },
      activeConfigData: {
        get() {
          const pageDataStr = (this.pageDataStore[this.activeMenuKey] || {}).pageData;
          const expectedType = this.activeMenu.dataType; // 获取期望的数据类型

          if (!pageDataStr) {
            return expectedType === 'array' ? [] : {};
          }
          try {
            const parsed = JSON.parse(pageDataStr);
            if (expectedType === 'array' && Array.isArray(parsed)) return parsed;
            if (expectedType === 'object' && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;
            // 如果解析出的类型与期望不符，也返回正确的空结构
            return expectedType === 'array' ? [] : {};
          } catch (e) {
            return expectedType === 'array' ? [] : {};
          }
        },
        set(newValue) {
          if (!this.pageDataStore[this.activeMenuKey]) {
            this.$set(this.pageDataStore, this.activeMenuKey, {});
          }
          this.pageDataStore[this.activeMenuKey].pageData = JSON.stringify(newValue);
        }
      }
    },
    created() {
      this.loadConfig(this.activeMenuKey);
    },
    methods: {
      handleMenuSelect(key) {
        if (this.activeMenuKey === key) return;
        this.activeMenuKey = key;
        this.loadConfig(key);
      },
      loadConfig(key) {
        this.loading = true;
        const menu = this.pageMap[key];
        getPageData(menu.type).then(response => {
          const pageData = response.data || {
            pageType: menu.type,
            pageData: null
          };
          this.$set(this.pageDataStore, key, pageData);
        }).finally(() => {
          this.loading = false;
        });
      },
      handleSave() {
        this.saving = true;
        const dataToSave = this.pageDataStore[this.activeMenuKey];
        savePageData(dataToSave).then(() => {
          this.$modal.msgSuccess("保存成功");
        }).finally(() => {
          this.saving = false;
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  .page-decoration-container {
    background: #f0f2f5;
  }

  .page-decoration {
    display: flex;
    height: calc(100vh - 84px); // 占满若依主内容区的高度
    margin: -20px; // 抵消若依 app-container 的默认 padding
  }

  .left-panel {
    width: 200px;
    background: #fff;
    border-right: 1px solid #e8e8e8;
    padding-top: 10px;

    .menu {
      border-right: none;
    }
  }

  .main-panel {
    flex: 1;
    display: flex;
    height: 100%;
  }

  .center-panel {
    flex: 1;
    background: #f7f8fa;
    display: flex;
    justify-content: center;
    align-items: flex-start;
    /* 改为从顶部对齐 */
    padding: 20px;
    overflow-y: auto;
  }

  .right-panel {
    width: 450px;
    background: #fff;
    border-left: 1px solid #e8e8e8;
    padding: 20px;
    overflow-y: auto;
  }

  .footer-bar {
    position: absolute;
    bottom: 0;
    left: 200px;
    /* 与左侧菜单同宽 */
    right: 0;
    height: 60px;
    background: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
    z-index: 99;
  }

  .mobile-preview-wrapper {
    width: 375px;
    min-height: 667px;
    background-color: #fff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    border-radius: 20px;
    border: 8px solid #333;
    overflow: hidden;
  }

  .mobile-header {
    height: 44px;
    line-height: 44px;
    text-align: center;
    font-weight: bold;
    border-bottom: 1px solid #eee;
    background-color: #fff;
  }

  .mobile-body {
    flex: 1;
    overflow-y: auto;
    background: #f7f8fa;
  }

  .preview-component-wrapper {
    position: relative;

    &:hover .preview-overlay {
      border-color: #409EFF;
    }

    &:hover .preview-drag-handle,
    &:hover .preview-actions {
      display: block;
    }
  }

  .preview-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    border: 2px dashed transparent;
    cursor: move;
    pointer-events: none;
    /* 让鼠标事件可以穿透到下层 */
  }

  .preview-drag-handle {
    position: absolute;
    top: 0;
    left: 0;
    background: #409EFF;
    color: white;
    padding: 2px 8px;
    font-size: 12px;
    display: none;
    border-bottom-right-radius: 4px;
    pointer-events: all;
    /* 手柄可以被交互 */
  }

  .preview-actions {
    position: absolute;
    top: 0;
    right: 0;
    display: none;
    pointer-events: all;
    /* 按钮可以被交互 */
  }
</style>
